<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :model-value="visible"
      title="钢卷库存选择"
      width="1200px"
      draggable
      destroy-on-close
      align-center
      @close="closeDialog"
      class="personDialog"
      append-to-body
    >
      <el-row :gutter="20">
        <!-- 用户列表 -->
        <el-col :span="20">
          <div shadow="never" class="search-container">
            <el-form
              ref="queryFormRef"
              :model="searchParam"
              :inline="true"
              label-width="90"
              label-position="left"
              class="dialogSeach"
            >
              <el-form-item label="存货">
                <el-select
                  @keyup.enter="search"
                  v-model="searchParam.materialId"
                  placeholder="请选择存货编码"
                  clearable
                  disabled
                >
                  <el-option
                    v-for="item in materialInfoTree"
                    :key="item.id"
                    :label="`${item.materialCode}-${item.materialName}`"
                    :value="item.materialId"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="仓库">
                <el-select
                  @keyup.enter="search"
                  v-model="searchParam.warehouseId"
                  placeholder="请选择仓库"
                  clearable
                  @change="selectWarehouse"
                >
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.id"
                    :label="item.warehouseName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="存储类型">
                <el-select
                  @keyup.enter="search"
                  v-model="searchParam.storageTypeId"
                  placeholder="请选择存储类型"
                  clearable
                >
                  <el-option
                    v-for="item in storageTypeList"
                    :key="item.id"
                    :label="item.storageTypeName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="计划数量">
                <el-input v-model="props.planQuantity" disabled />
              </el-form-item>
              <el-form-item label="总重量(kg)">
                <el-input v-model="AllKg" disabled />
              </el-form-item>
              <el-form-item label="总理论数量">
                <el-input v-model="AllNum" disabled />
              </el-form-item>
              <el-form-item label="已锁定库存">
                <el-switch
                  v-model="searchParam.lockedStatus"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
              <el-form-item class="ml-[5px]">
                <el-button type="primary" @click="beforeSearch"
                  ><i-ep-search />搜索</el-button
                >
                <el-button @click="reset"> <i-ep-refresh />重置 </el-button>
              </el-form-item>
            </el-form>
          </div>
          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableData"
            row-key="materialBarcode"
            @select="handleSelectionChange"
            @select-all="handleAllChange"
            height="420px"
            border
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              label="条码号"
              prop="materialBarcode"
              align="center"
              width="180"
              show-overflow-tooltip
            />
            <el-table-column
              label="批次号"
              prop="stockBatch"
              align="center"
              width="180"
              show-overflow-tooltip
            />
            <el-table-column
              label="重量(kg)"
              prop="materialWeight"
              align="right"
              width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="理论数量"
              prop="theoryQuantity"
              align="right"
              width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="锁定状态"
              prop="lockedStatus"
              align="center"
              width="100"
              show-overflow-tooltip
            >
              <template #default="{ row, $index }">
                <el-tag class="text-[13px]" v-if="row.lockedStatus === 0"
                  >未锁定</el-tag
                >
                <el-tag type="warning" class="text-[13px]" v-else
                  >已锁定</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              label="锁定计划"
              prop="producePlanCode"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="存储类型"
              prop="storageTypeName"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="货位"
              prop="binCode"
              align="center"
              show-overflow-tooltip
            />
          </el-table>
        </el-col>

        <!-- 回显树 -->
        <el-col
          :span="4"
          style="box-shadow: 0px 0px 12px rgba(3, 8, 72, 0.08)"
          class="!p-[0px] h-auto"
        >
          <div>
            <el-row class="p-[15px]">
              <el-col :span="18">
                <div class="selectText">
                  已选卷料(<span style="color: #0080ff">{{
                    totalMultipleSelection.length
                  }}</span
                  >)
                </div>
              </el-col>
              <el-col :span="6" align="right">
                <el-button
                  v-show="!readonly"
                  size="small"
                  type="danger"
                  @click="delAll"
                  link
                  >清空</el-button
                >
              </el-col>
            </el-row>

            <el-scrollbar height="400px">
              <div>
                <el-row
                  v-for="(item, index) in totalMultipleSelection"
                  :key="index"
                  class="hover-b-blue pl-[14px] pr-[14px] name"
                >
                  <el-col :span="20">{{ item.materialBarcode }}</el-col>
                  <el-col :span="4" align="right" v-show="!readonly">
                    <i-ep-CircleCloseFilled
                      class="c-[rgba(0,0,0,.15)]"
                      @click="delSingle(item, index)"
                    />
                  </el-col>
                </el-row>
              </div>
            </el-scrollbar>
          </div>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import { ElTable } from "element-plus";
import request from "@/utils/request";
import { useRoute, useRouter } from "vue-router";
import { getWarehouseList, getStorageTypeList } from "@/utils/commonData";
import { mockResPlans } from "@/views/mes/weeklyProducePlan/index";
const route = useRoute();

defineOptions({
  name: "SelectMaterialPlanDialog",
  inheritAttrs: false,
});

interface SelectOption {
  id?: string;
}
const emit = defineEmits(["update:visible", "echo-info"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Array,
    default: () => {
      return [];
    },
  },
  isMultiple: {
    type: Boolean,
    default: true,
  },
  allocationId: {
    type: String,
    default: "",
  },
  plantId: {
    type: String,
    default: "",
  },
  planQuantity: {
    type: [String, Number],
    default: "",
  },
  rowIndex: {
    type: [String, Number],
    default: "",
  },
  readonly: {
    type: Boolean,
    default: true,
  },
  eldIds: {
    type: Array,
    default: () => {
      return [];
    },
  },
  companyId: {
    type: String,
    default: "",
  },

  materialId: {
    type: String,
    default: "",
  },
  materialCode: {
    type: String,
    default: "",
  },
});

const {
  visible,
  isMultiple,
  allocationId,
  plantId,
  companyId,
  rowIndex,
  readonly,
  eldIds,
  planQuantity,
  materialId,
  materialCode,
} = toRefs(props);

// const checkSelectable = (row: any) => {
//   if (readonly.value === true) {
//     return false;
//   } else {
//     if (
//       row.lockedStatus === 0 ||
//       (row.lockedStatus === 1 && eldIds.value.includes(row.materialBarcode))
//     ) {
//       return true;
//     } else {
//       return false;
//     }
//   }
// };

// 设备状态字段
const equipStatusTree = ref([]);

// 获取存货编码下拉树
const materialInfoTree: any = ref([]);
const getMaterialInfoTree = async () => {
  const { data } = await request({
    url: `/mes/mesroutingbom/listMainMaterial/${allocationId.value}`,
    method: "GET",
    data: {},
  });
  materialInfoTree.value = data;

  if (data && data.length) {
    searchParam.value.materialId = materialId.value;
    searchParam.value.materialCode = materialCode.value;
  }
};

// 仓库列表
const warehouseList: any = ref([]);

// 存储类型列表
const storageTypeList: any = ref([]);

// 仓库选择
async function selectWarehouse(e) {
  if (e) {
    storageTypeList.value = await getStorageTypeList(e);
  } else {
    storageTypeList.value = [];
    searchParam.value.storageTypeId = "";
  }
}

function resetParams() {
  searchParam.value = searchParamInit;
  reset();
}

// 深层拷贝
function deepCopy(val: any) {
  return JSON.parse(JSON.stringify(val));
}

// 表格选择
const hh = ref(false);
const totalMultipleSelection: any = ref([]);
// 表格触发全选
function handleAllChange(selecteds: any) {
  if (isMultiple.value) {
    hh.value = !hh.value;
    const currentSelection = deepCopy(totalMultipleSelection.value);
    const ids = deepCopy(totalMultipleIds.value);
    if (selecteds.length) {
      const list = [];
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.materialBarcode);
        if (indexId < 0) {
          list.push(item);
        }
        if (
          item.lockedStatus === 1 &&
          eldIds.value.includes(item.materialBarcode)
        ) {
          list.push(item);
        }
        list.push(item);
      });
      totalMultipleSelection.value = deepCopy(selecteds);
    } else {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.materialBarcode);
        if (indexId > -1) {
          currentSelection.splice(indexId, 1);
          ids.splice(indexId, 1);
        }
      });
      totalMultipleSelection.value = deepCopy(currentSelection);
    }
  } else {
    delAll();
    ElMessage.warning("单选，请重新选择");
  }
}
// 表格触发单个选择
function handleSelectionChange(val: any, row: SelectOption) {
  // multipleTable.value.toggleAllSelection();
  console.log(deepCopy(val));
  console.log("---111---");
  let addOptions = false;
  val?.map((item: SelectOption) => {
    if (item?.materialBarcode === row?.materialBarcode) {
      console.log("materialBarcode", row?.materialBarcode);
      addOptions = true;
    }
  });

  console.log("addOptions", addOptions, row, val);

  if (!addOptions) {
    const index = totalMultipleIds.value.indexOf(row.materialBarcode);

    totalMultipleSelection.value.splice(index, 1);
  } else {
    if (isMultiple.value) {
      totalMultipleSelection.value.push(row);
    } else {
      delAll();
      multipleTable.value.toggleRowSelection(row, true);
      totalMultipleSelection.value = [row];
    }
  }
}
// 后加的代码-- 计算所有重量
// 总重量
const AllKg = computed(() => {
  let sum = 0;
  totalMultipleSelection.value?.map((item) => {
    sum += Number(item.materialWeight);
  });
  return sum;
});

// 总数量
const AllNum = computed(() => {
  let sum = 0;
  totalMultipleSelection.value?.map((item) => {
    sum += item.theoryQuantity;
  });
  return sum;
});

// 右侧人员选择操作
const multipleTable = ref(ElTable);
// 全部清除
function delAll() {
  totalMultipleSelection.value = [];
  multipleTable.value.clearSelection();
}
// 单个删除
function delSingle(current: SelectOption, index: number) {
  totalMultipleSelection.value.splice(index, 1);
  tableData.value.map((item: SelectOption) => {
    if (item.materialBarcode === current.materialBarcode) {
      multipleTable.value.toggleRowSelection(item, false);
    }
  });
}

/** 弹窗展开 初始化数据 */
const totalMultipleIds: any = ref([]);
watch(
  () => totalMultipleSelection,
  async (newVal: any) => {
    const ids: any = [];
    newVal.value?.map((item: SelectOption) => {
      // console.log("newVal.value", item);
      ids.push(item.materialBarcode);
    });

    console.log("---5222---");
    totalMultipleIds.value = ids;
  },
  { deep: true }
);

// 请求参数
const requestApi = "/mes/mesMaterialSelect/listStorageMainMaterial";

// 是否需要分页
const pagination = false;

const initParam = reactive({});

// 初始化搜索参数数据
const searchParamInit = {
  routingAllocationId: "",
  lockedStatus: "",
  materialCode: "",
  materialId: "",
  storageTypeId: "",
  warehouseId: "",
  plantId: "",
};

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
function dataCallBack(data: any) {
  setTimeout(() => {
    data.map((item: SelectOption) => {
      if (totalMultipleIds.value.includes(item.materialBarcode)) {
        multipleTable.value.toggleRowSelection(item, true);
      }
    });
  }, 0);
  return data;
}

// 表格操作 Hooks
const { tableData, searchParam, loading, getTableList }: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError
);

function reset() {
  searchParam.value = {
    ...searchParam.value,
    storageTypeId: "",
    warehouseId: "",
    lockedStatus: "",
  };
  search();
}

onMounted(async () => {
  // getTableList();
  // search();
  // workShopList.value = (await getWorkShopList(route.query.plantId || "")) ?? [];
});

const beforeSearch = () => {
  if (!searchParam.value.plantId || !searchParam.value.warehouseId) {
    ElMessage.error("请选择存货编码和仓库");
    return;
  } else {
    search();
  }
};
/** 弹窗展开 初始化数据 */
const oldTotalSelection: any = ref([]);
const oldTotalSelectionIds: any = ref([]);
watch(
  () => props.visible,
  async (newVal: boolean) => {
    if (newVal) {
      getMaterialInfoTree();
      searchParam.value.plantId = plantId.value;
      searchParam.value.routingAllocationId = allocationId.value;
      warehouseList.value = await getWarehouseList(companyId.value);
      if (warehouseList.value.length) {
        searchParam.value.warehouseId = warehouseList.value[0].id;
        storageTypeList.value = await getStorageTypeList(
          warehouseList.value[0].id
        );
      } else {
        storageTypeList.value = [];
      }
      // getLocationInfoTree();
      // getMdmequiptypeTree();
      equipStatusTree.value = useDictionary("EquipStatus");

      totalMultipleSelection.value = deepCopy(props.data);
      oldTotalSelection.value = deepCopy(props.data);
      const ids = [];
      oldTotalSelection.value?.map((item) => {
        ids.push(item.materialBarcode);
      });
      oldTotalSelectionIds.value = ids;
      dataCallBack(tableData.value);
      setTimeout(() => {
        search();
      }, 300);
    } else {
      searchParam.value.warehouseId = "";
      searchParam.value.routingAllocationId = "";
      warehouseList.value = [];
      selectWarehouse("");
      tableData.value = [];
    }
  }
);

async function search() {
  const params = JSON.parse(JSON.stringify(searchParam.value));
  if (params.lockedStatus === 1) {
    delete params.lockedStatus;
  }
  loading.value = true;
  const { data } = await request({
    url: requestApi,
    method: "post",
    data: params,
  }).finally(() => {
    loading.value = false;
  });
  tableData.value = data;
  dataCallBack(tableData.value);
}

/** 关闭表单弹窗 */
function closeDialog() {
  totalMultipleSelection.value = oldTotalSelection.value;
  dataCallBack(tableData.value);
  emit("update:visible", false);
}

/** 确定提交 */
async function handleSubmit() {
  if (!isMultiple.value && totalMultipleSelection.value.length > 1) {
    ElMessage.error("请选择单个人员");
  } else {
    if (totalMultipleSelection.value.length > 0) {
      totalMultipleSelection.value.sort(function (a, b) {
        return Number(a.stockBatch) - Number(b.stockBatch);
      });
      if (totalMultipleSelection.value.length) {
        if (getUncheckedRows().length > 0) {
          if (
            typeof Number(getUncheckedRows()[0].stockBatch) == "number" &&
            typeof Number(
              totalMultipleSelection.value[
                totalMultipleSelection.value.length - 1
              ].stockBatch
            ) == "number"
          ) {
            if (
              Number(
                totalMultipleSelection.value[
                  totalMultipleSelection.value.length - 1
                ].stockBatch
              ) > Number(getUncheckedRows()[0].stockBatch)
            ) {
              ElMessage.warning("请先选择较早批次卷料！");
              // ElMessageBox.confirm("选择项不符合先进先出原则是否继续?", "警告", {
              //   confirmButtonText: "确定",
              //   cancelButtonText: "取消",
              //   type: "warning",
              // }).then(() => {
              //   emit("update:visible", false);
              //   emit(
              //     "echo-info",
              //     totalMultipleSelection.value,
              //     rowIndex.value,
              //     AllKg.value,
              //     AllNum.value
              //   );
              // });
            } else {
              emit("update:visible", false);
              emit(
                "echo-info",
                totalMultipleSelection.value,
                rowIndex.value,
                AllKg.value,
                AllNum.value
              );
            }
          } else {
            emit("update:visible", false);
            emit(
              "echo-info",
              totalMultipleSelection.value,
              rowIndex.value,
              AllKg.value,
              AllNum.value
            );
          }
        } else {
          emit("update:visible", false);
          emit(
            "echo-info",
            totalMultipleSelection.value,
            rowIndex.value,
            AllKg.value,
            AllNum.value
          );
        }
      }

      // emit("update:visible", false);
      // emit(
      //   "echo-info",
      //   totalMultipleSelection.value,
      //   rowIndex.value,
      //   AllKg.value,
      //   AllNum.value
      // );
    } else {
      ElMessage.warning("请选择卷料！");
    }
  }
}

const getUncheckedRows = () => {
  const checkedRows = totalMultipleSelection.value;
  const allRows = tableData.value;
  const uncheckedRows = allRows.filter((row) => {
    return !checkedRows.some(
      (checkedRow) => checkedRow.storageUnitId === row.storageUnitId
    );
  });
  return uncheckedRows;
};

// 组件销毁时调用
onBeforeUnmount(() => {
  emit("update:visible", false);
  closeDialog();
});
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding: 20px 20px 0 20px;
}
.name:hover {
  background-color: rgb(236, 245, 255) !important;
  color: var(--el-menu-active-color) !important;
  border-radius: 6px;
  svg {
    color: var(--el-menu-active-color) !important;
  }
}
.name svg {
  cursor: pointer;
}
:deep(.el-form--inline .el-form-item) {
  margin-right: 18px;
  margin-bottom: 14px;
}
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color))
    inset !important;
}
.el-button svg {
  margin-right: 0;
}
.card-table-p15 {
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  .card-table {
    line-height: normal;
  }
}

:deep(.el-tree) {
  height: 533px;
}
:deep(.dialogSeach .el-form-item__label-wrap) {
  margin-right: 15px !important;
}
:deep(.dialogSeach .el-form--inline .el-form-item) {
  margin-right: 30px !important;
}
</style>
